import React, { Component } from "react";
import {Form,Input,Select,Table,Divider,Button,Modal,DatePicker,Row,Col,Upload} from "antd";
import Content from "../../components/Content/Content";
import {  InputNumber, Popconfirm, } from 'antd';

const EditableContext = React.createContext();

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `Please Input ${title}!`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);

    this.state = { 
      dataSource: [], 
      editingKey: '' ,     
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,

      keyword: '',
    
      count: 0,
      loading: true,
      pageNum: 1,
      pageSize: 100

    };

    this.columns = [
      {
        title: '序号',
        dataIndex: 'id',
        fixed: 'left',
        width:100,
        editable: true,
      },
      {
        title: '新增分离菌株编号',
        dataIndex: 'add_separate_num',
        fixed: 'left',
        width:200,
        editable: true,
      },
      {
        title: '采集样品编号',
        dataIndex: 'Acq_id',
        editable: true,
      },
      {
        title: '采集样品预处理方法',
        dataIndex: 'add_method',
        editable: true,
      },
      {
        title: '菌种类别',
        dataIndex: 'add_jzlb',
       
      },
      {
        title: '属名',
        dataIndex: 'add_sm',
       
      },
      {
        title: '近缘菌株',
        dataIndex: 'add_jyjz',
        editable: true,
      },
      {
        title: '与近缘菌株最高相似性(%)',
        dataIndex: 'add_flid',
        editable: true,
      },
      {
        title: '菌株图片',
        dataIndex: 'add_pic',
      },
      {
        title: '菌株序列',
        dataIndex: 'info_jyxl',
        children: [
         
        ],
      },
      // children start
      {
        title: '细菌',
        dataIndex: 'add_xj',
      },
      {
        title: '真菌',
        dataIndex: 'add_zj',
      },
      {
        title: '放线菌',
        dataIndex: 'add_fxj',
      },
      {
        title: '其他',
        dataIndex: 'add_qtjzlx',
      },
      
      // children end

      {
        title: '基因序列原始文件',
        dataIndex: 'info_jyxlwj',
       
      },
      {
        title: '分离培养基',
        dataIndex: 'add_flpyjid',
        editable: true,
      },
      {
        title: '传代培养基',
        dataIndex: 'add_cdpyjid',
        editable: true,
      },
      {
        title: '分离人',
        dataIndex: 'add_person',
        editable: true,
      },
      {
        title: "分离时间",
        dataIndex: "add_time",
      },
      {
        title: '工作人员',
        dataIndex: 'worker',
        editable: true
      },
      {
        title: '编辑',
        dataIndex: 'operation',
        fixed:'right',
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <a
                    onClick={() => this.save(form, record)}
                    style={{ marginRight: 8 }}
                  >
                    保存
                  </a>
                )}
              </EditableContext.Consumer>
              <Popconfirm title="确认取消吗?" onConfirm={() => this.cancel(record.id)}>
                <a>取消</a>
              </Popconfirm>
            </span>
          ) : (
            <a disabled={editingKey !== ''} onClick={() => this.edit(record.id)}>
              编辑
            </a>
          );
        },
      },
      {
        title:'操作',
        fixed: 'right',
        width:500,
        render: (text, record) => (
                <span>
                  <Button  type="dashed" disabled={record.chuli_tag == 'yhj'} id={'huijiao1_' + record.id} onClick={this.huijiao.bind('click', {record: record, chuli_tag: 'yhj', jzjz_tag: 'pt'})}>
                    筛选菌株汇交
                  </Button>
                  <Divider type="vertical" />
                  <Button type="dashed" disabled={record.chuli_tag == 'yhj'} id={'huijiao2_' + record.id} onClick={this.huijiao.bind('click', {record: record, chuli_tag: 'yhj', jzjz_tag: 'qzxwz' })}>
                    潜在新物种
                  </Button>
                  <Divider type="vertical" />
                  <Button type="dashed" disabled={record.chuli_tag == 'yhj'} id={'huijiao3_' + record.id} onClick={this.huijiao.bind('click', {record: record, chuli_tag: 'yhj', jzjz_tag: 'dyx' })}>
                    多样性汇交
                  </Button>
                  <Divider type="vertical" />
                  <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
                    <Button type="dashed" >删除</Button>
                  </Popconfirm>
                </span>
              )
      },
 
    ];
  }

  isEditing = record => record.id === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: '' });
  };

  loadData = (current) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    if( !current ) current = 1;

    const url = global.api.strainInfo;
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: this.state.keyword})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count, loading: false})
    })
    .catch(err => {
      Modal.error({
        content: '加载数据出错！'
      });
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  handleDelete = id => {
    const url = global.api.strainInfo + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    }) 
  };

  huijiao = (params) => {
    let record = params.record;

    let jzjz_tag_before = record.jzjz_tag;
    let chuli_tag_before = record.chuli_tag;

    let chuli_tag = params.chuli_tag;
    let jzjz_tag = params.jzjz_tag;

    record.chuli_tag = chuli_tag;
    record.jzjz_tag = jzjz_tag;

    const url = global.api.strainInfo + record.id + '/';
    return global.updatedata.put(url, record)
    .then(res => {  

      this.loadData(1);

      Modal.success({
        content: '汇交成功!',
      });
    })
    .catch(err => {
        
      record.chuli_tag = chuli_tag_before;
      record.jzjz_tag = jzjz_tag_before;
      
      Modal.error({
        content: '汇交出错!',
      });
    }) 

  }

  save(form, record) {
    
      // 保存数据
      const url = global.api.strainInfo + record.id + '/';
      return global.updatedata.put(url, record)
      .then(res => {

        this.loadData(1);     

        Modal.success({
          content: '保存成功！'
        });

        this.cancel();
      })
      .catch(err => {
        Modal.error({
          content: 'Err: 保存失败！'
        })
      }) 

  }

  edit(id) {
    this.setState({ editingKey: id });
  }
  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };
    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <Content>
         <div className="filtrate">
          <p style={{marginLeft:'100px'}}>
          <span className="span">
         <Input placeholder="输入查询内容" style={{ width: 500 }}  onChange={e => this.setState({keyword: e.target.value})}/>
          </span>
          <span className="span" >
            <Button type="primary" style={{ width: 80 }} onClick={this.loadData.bind('click', 1)}>
              查询
            </Button>
          </span>
          </p>
        </div>
        <Button
          type="primary"
          onClick={this.start}
          disabled={!hasSelected}
          loading={loading}
          style={{marginLeft:20,marginTop:20}}
        >
          导出
        </Button>
        <span style={{ marginLeft: 8 }}>
          {hasSelected ? `选中 ${selectedRowKeys.length} 个` : ""}
        </span>
      <EditableContext.Provider value={this.props.form}>
        <Table
          rowSelection={rowSelection}
          components={components}
          bordered
          dataSource={this.state.dataSource}
          columns={columns}
          rowClassName="editable-row"
          pagination={{
            onChange: this.cancel,
          }}
          scroll={{ x: 3000}}
        />
      </EditableContext.Provider>
      </Content>
    );
  }
}

const CompoundInfo = Form.create()(EditableTable);

export default CompoundInfo;
